package com.itjiange.service.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itjiange.common.common.ErrorCode;
import com.itjiange.common.exception.BusinessException;
import com.itjiange.model.dto.user.UserQueryRequest;
import com.itjiange.model.entity.User;
import com.itjiange.model.enums.UserRoleEnum;
import com.itjiange.model.vo.LoginUserVO;
import com.itjiange.model.vo.UserVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static com.itjiange.common.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务
 *
 * @author <a href="https://gitee.com/yijian-smiles">一健憨笑</a>
 * @from <a href="https://gitee.com/yijian-smiles/yijian-oj">一健 oj 判題系統</a>
 */
@FeignClient(name = "yijian-backend-user-service-9101", path = "/api/user/inner")
public interface UserFeignClient {

    /**
     * 通过用户 id 获取 User
     * @param userId
     * @return
     */
    @GetMapping("/get/{id}")
    User getById(@PathVariable("id") long userId);

    /**
     * 获取脱敏的用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/get/user")
    UserVO getUserVO(@RequestBody User user);

    /**
     * 批量获取用户信息
     * @param userIdSet
     * @return
     */
    @PostMapping("/get/users")
    List<User> listByIds(@RequestBody Collection<Long> userIdSet);

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    default User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    default boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
    default boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
}
